import { EventEmitter } from 'events';

interface Command {
    data: string | Buffer;
    priority: number;
    timestamp: number;
}

class CommandQueue {
    private queue: Command[] = [];
    private isProcessing: boolean = false;
    private eventEmitter: EventEmitter;
    private static instance: CommandQueue;

    private constructor() {
        this.eventEmitter = new EventEmitter();
    }

    public static getInstance(): CommandQueue {
        if (!CommandQueue.instance) {
            CommandQueue.instance = new CommandQueue();
        }
        return CommandQueue.instance;
    }

    public addCommand(data: string | Buffer, priority: number = 0): void {
        const command: Command = {
            data,
            priority,
            timestamp: Date.now()
        };
        
        this.queue.push(command);
        this.queue.sort((a, b) => {
            // 首先按优先级排序
            if (a.priority !== b.priority) {
                return b.priority - a.priority;
            }
            // 如果优先级相同，按时间戳排序
            return a.timestamp - b.timestamp;
        });

        if (!this.isProcessing) {
            this.processNextCommand();
        }
    }

    private async processNextCommand(): Promise<void> {
        if (this.queue.length === 0) {
            this.isProcessing = false;
            return;
        }

        this.isProcessing = true;
        const command = this.queue.shift();
        
        if (command) {
            this.eventEmitter.emit('sendCommand', command.data);
            // 等待一小段时间确保命令被处理
            await new Promise(resolve => setTimeout(resolve, 100));
            this.processNextCommand();
        }
    }

    public onSendCommand(callback: (data: string | Buffer) => void): void {
        this.eventEmitter.on('sendCommand', callback);
    }

    public clearQueue(): void {
        this.queue = [];
        this.isProcessing = false;
    }

    public getQueueLength(): number {
        return this.queue.length;
    }
}

export default CommandQueue; 